// pages/addOwner/addOwner.js
//获取应用实例
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
const storage = require('../../utils/storage');
const util = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    // 底部菜单高度
    tabbarHeight: app.globalData.tabbarHeight,
    BASEURLWWW:constant.BASEURLWWW,
    BASEURL: constant.BASEURL,
    // 头部标题
    title: '添加货主',
    // 标签列表
    noteList: [],
    // 头像
    ownerDetail: {
      avatar_url: '',
      owner_name: '',
      owner_address: '',
      owner_tel: [],
      owner_tags: [],
      owner_remark: '',
      from_pos_id: 0
    },
    // 临时电话号码
    owner_tel: null,
    // 备注字数
    remarkNum: 0
  },
  onLoad(option){
    if(option.owner_id){
      console.info(option.owner_id)
      this.setData({
        title: '编辑货主'
      })
      this.getOwnerDetailsData(option.owner_id)
    }
  },
  onShow(){
    this.getNoteListData()
  },
  // 获取货主详情信息
  getOwnerDetailsData(owner_id){
    let ownerDetail = this.data.ownerDetail
    api.showOwner({owner_id}).then(res => {
      console.info(res)
      if(res.code == 0){
        ownerDetail = {...res.data.data}
        this.setData({
          ownerDetail
        })
        this.tagsCount()
      }
    })
  },
  // 获取标签列表
  getNoteListData(){
    api.getNoteListData({type: 1}).then(res => {
      if(res.code == 0){
        res.data.data.list.forEach(item => {
          item.isChoose = false
        })
        this.setData({
          noteList: [...res.data.data.list]
        })
        console.info(this.data.ownerDetail)
        if(this.data.ownerDetail.user_id){
          this.tagsCount()
        }
      }
    })
  },
  // 上传图片
  uploadImg(e){
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        wx.uploadFile({
          url: `${that.data.BASEURL}/myfile/wechat`, //仅为示例，非真实的接口地址
          filePath: res.tempFilePaths[0],
          name: 'file',
          header:{
            'Authorization': 'Bearer '+ wx.getStorageSync(storage.LOCAL_JWT_KEY),
            'Deviceid': 'loveqing'
          },
          formData: {},
          success (res){
            let jsonObj = JSON.parse(res.data)
            if(jsonObj.code == 0){
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              })
              that.setData({
                'ownerDetail.avatar_url': jsonObj.data.uri
              })
            }else{
              wx.showToast({
                title: jsonObj.msg,
                icon: 'error'
              })
            }
          }
        })
      }
    })
  },
  // input获取值
  inputChange(e){
    let name = e.currentTarget.dataset.name
    let value = e.detail.value.trim()
    if(name == 'owner_name'){ // 货主姓名
      this.setData({
        'ownerDetail.owner_name': value
      })
    }
    if(name == 'owner_address'){ // 地址
      this.setData({
        'ownerDetail.owner_address': value
      })
    }
    if(name == 'owner_tel'){ // 电话号码
      this.setData({
        owner_tel: value
      })
    }
    if(name == 'remark'){
      let remarkNum = value.length
      if(remarkNum <= 500){
        this.setData({
          remarkNum,
          'ownerDetail.remark': value
        })
      }
    }
  },
  // 添加电话号码
  addPhoneNumber(){
    let owner_tel = this.data.owner_tel
    let owner_telArr = this.data.ownerDetail.owner_tel
    if(!util.checkPhone(owner_tel)){
      wx.showToast({
        title: '电话号码不正确！',
        icon: 'none'
      })
    }else{
      let off = true
      owner_telArr.forEach(item => {
        if(item.owner_tel == owner_tel){
          wx.showToast({
            title: '电话号码已存在！',
            icon: 'none'
          })
          off = false
        }
      })
      if(off){
        owner_telArr.push({owner_tel})
        this.setData({
          'ownerDetail.owner_tel': owner_telArr,
          owner_tel: null
        })
      }
    }
  },
  // 删除电话号码
  deletePhone(e){
    let index = e.currentTarget.dataset.index
    let owner_tel = this.data.ownerDetail.owner_tel
    owner_tel.splice(index,1)
    this.setData({
      'ownerDetail.owner_tel': owner_tel
    })
  },
  // 跳转到url
  jumptoUrl(e){
    console.info(e.currentTarget.dataset.url)
    wx.navigateTo({
      url: `${e.currentTarget.dataset.url}?isNotePopShow=true`
    })
  },
  // 标签选择
  chooseTags(e){
    let tags_id = e.currentTarget.dataset.id
    let noteList = this.data.noteList
    let owner_tags = this.data.ownerDetail.owner_tags
    noteList.forEach((item,index) => {
      if(!item.isChoose && tags_id == item.tags_id){
        owner_tags.push({tags_id: item.tags_id})
      }
      if(item.isChoose && tags_id == item.tags_id){
        owner_tags.forEach((node,num) => {
          if(node.tags_id == tags_id){
            owner_tags.splice(num,1)
          }
        })
      }
    })
    this.setData({
      'ownerDetail.owner_tags': owner_tags
    })
    console.info(this.data.ownerDetail.owner_tags)
    this.tagsCount()
  },
  // 标签计算
  tagsCount(){
    let noteList = this.data.noteList
    let owner_tags = this.data.ownerDetail.owner_tags
    let tagsArr = []
    owner_tags.forEach(item => {
      tagsArr.push(item.tags_id)
    })
    noteList.forEach(item => {
      if(tagsArr.includes(item.tags_id)){
        item.isChoose = true
      }else{
        item.isChoose = false
      }
    })
    this.setData({
      noteList
    })
  },
  // 保存
  save(){
    let ownerDetail = this.data.ownerDetail
    console.info(ownerDetail)
    if(ownerDetail.user_id){ // 编辑
      api.updateOwner(ownerDetail).then(res => {
        console.info(res)
      })
    }else{ 添加
      if(ownerDetail.owner_name == ''){
        wx.showToast({
          title: '货主姓名不能为空！',
          icon: 'none'
        })
        return
      }
      api.addOwner(ownerDetail).then(res => {
        console.info(res)
        if(res.code == 0){
          wx.reLaunch({
            url: '/pages/mailList/mailList',
          })
        }
      })
    }
  },
  // 返回到通讯录
  back:function(){
    wx.reLaunch({
      url: '/pages/mailList/mailList'
    })
  },
  // 背景不滚动
  dontMove: function(){
    return;
  },
  
})